package com.clp.protocol.iec104.iec104.apdu.apci;

import com.clp.protocol.core.nbytepdu.BaseNBytePduClip;
import com.clp.protocol.core.pdu.ByteToStringFormat;
import com.clp.protocol.iec104.iec104.definition.ConstVal;
import com.clp.protocol.iec104.iec104.definition.UCtrlType;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.Objects;
import java.util.function.Consumer;

@Getter
@NoArgsConstructor
@AllArgsConstructor
public class UCtrlArea extends CtrlArea<UCtrlArea> {
    /**
     * U帧的控制类型（共6种）
     */
    private UCtrlType uCtrlType;

    @Override
    public UCtrlArea refreshFrom(ByteBuf buf) {
        byte[] controlAreaBytes = new byte[ConstVal.CTRL_AREA_LEN];
        buf.readBytes(controlAreaBytes);
        this.uCtrlType = UCtrlType.gain(controlAreaBytes);
        return this;
    }

    @Override
    public boolean isValid() {
        return uCtrlType != null;
    }

    @Override
    public void writeBytesTo(ByteBuf buf) {
        buf.writeBytes(uCtrlType.getUCtrlBytes());
    }

    @Override
    public void writeFormattedByteStringsTo(StringBuilder sb, String frameClipBytesSeparator, String byteSeparator, ByteToStringFormat byteFormat) {
        byte[] uCtrlBytes = uCtrlType.getUCtrlBytes();
        sb.append(byteFormat.format(uCtrlBytes[0]));
        for (int i = 1; i < uCtrlBytes.length; i++) {
            sb.append(byteSeparator).append(byteFormat.format(uCtrlBytes[i]));
        }
    }

    @Override
    public void writeSimpleDescriptionTo(StringBuilder sb) {
        sb.append(uCtrlType.getDesc());
    }

    @Override
    public void writeDetailDescriptionTo(StringBuilder sb) {
        sb.append("控制类型：").append(uCtrlType.getDesc());
    }

    @Override
    protected void forEachOneLevelChild(Consumer<BaseNBytePduClip<?>> consumer) {

    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        UCtrlArea that = (UCtrlArea) o;
        return uCtrlType == that.uCtrlType;
    }

    @Override
    public int hashCode() {
        return Objects.hash(uCtrlType);
    }
}
